package com.demo.mykotlin.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.demo.mykotlin.R
import com.demo.mykotlin.bean.LeftViewHolder
import com.demo.mykotlin.bean.MsgBean
import com.demo.mykotlin.bean.MsgViewHolder
import com.demo.mykotlin.bean.RightViewHolder

/**
 * 聊天消息适配器
 * @author wen66to88@163.com
 * @date 2020/5/22 - 10:42
 */
class MsgAdapter(val msgList: List<MsgBean>) : RecyclerView.Adapter<MsgViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        if (viewType == MsgBean.TYPE_RECEIVES) {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_msg_left, parent, false)
            LeftViewHolder(view)
        } else {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.item_msg_right, parent, false)
            RightViewHolder(view)
        }

    override fun getItemCount() = msgList.size

    /**
     * 使用密封类优化分支语句
     */
    override fun onBindViewHolder(holder: MsgViewHolder, position: Int) {
        val msg = msgList[position]
        when (holder) {
            is LeftViewHolder -> holder.leftMsg.text = msg.content
            is RightViewHolder -> holder.rightMsg.text = msg.content
        }
    }

    override fun getItemViewType(position: Int): Int {
        val msg = msgList[position]
        return msg.type
    }
}